﻿package net.wangit.adm.user;

import net.wangit.Unit;
import net.wangit.User;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.support.UnitInterceptor;
import net.wangit.user.AdminUser;
import net.wangit.user.UserFactory;
import net.wangit.user.admin.Admin;
import net.wangit.user.admin.AdminFactory;
import net.wangit.util.ArrayUtil;
import net.wangit.util.Checker;
import net.wangit.view.unit.UnitComponent;

public class ResetPasswordUI implements UnitInterceptor {

	private static final String USER_ID = "net.wangit.adm.user.ResetPasswordUI.userid";

	public ResetPasswordUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		String userId = ActionContextHelper.getRequest2Session(ac, "userid",
				"net.wangit.adm.user.ResetPasswordUI.userid", null);
		if (Checker.isEmpty(userId))
			return "no user was specified!";
		User targetUser = UserFactory.getUser(userId);
		if (targetUser == null)
			return "user not found!";
		User user = ac.getVisitor().getUser();
		if (user instanceof AdminUser) {
			Admin a = AdminFactory.getAdmin(user.get("adminid"));
			String orgs[] = a.getOrganizations();
			if (ArrayUtil.find(orgs, targetUser.getOrgId()) < 0)
				return "you could not manage this user!";
		}
		unit.setTitle((new StringBuilder(String.valueOf(((UnitComponent) unit)
				.getTitle()))).append(" - ").append(targetUser.getName())
				.append("(").append(userId).append(")").toString());
		unit.getElement("userid").setDefaultValue(userId);
		return unit.write(ac);
	}
}
